package com.geek.busness.continuous;

import com.geek.busness.config.ConfigLoader;
import com.geek.busness.view.Config;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.awt.event.KeyEvent;

/**
 * 鼠标连点器的逻辑实现
 * 基于Robot类
 */
@Slf4j
public class MouseContinuous {

	MouseContinuousThread thread;

	public void start(){
		if(thread != null){
			return;
		}
		thread = new MouseContinuousThread();
		//连点的间隔，后续要做成用户选项
		Config config = ConfigLoader.load();
		thread.setTime(config.getInterval());
		thread.start();
	}

	public void stop(){
		if(thread != null){
			thread.exist();
		}
		thread = null;
	}

	/**
	 * 用于连点的线程
	 */
	static class MouseContinuousThread extends Thread{

		//连点的间隔
		private int time;
		private boolean isExist;
		private Robot robot;

		public MouseContinuousThread() {
			this.isExist = false;
			this.time = 100;
			try {
				robot = new Robot();
			} catch (AWTException e) {
				e.printStackTrace();
			}
		}

		public void exist(){
			this.isExist = true;
		}

		@SneakyThrows
		@Override
		public void run() {
			log.debug("开启模拟鼠标左键点击");
			this.isExist = false;
			if(time < 10){
				time = 10;
			}
			while (true){
				robot.mousePress(KeyEvent.BUTTON1_MASK);
				Thread.sleep(time);
				if(isExist){
					log.debug("结束模拟鼠标左键点击");
					break;
				}
			}
		}

		public int getTime() {
			return time;
		}

		public void setTime(int time) {
			this.time = time;
		}
	}

}
